extends Node

@onready var layer = $UILayer
@onready var rank = $RankLayer

var save_file = "user://score.save"
var arr_score = []

func save_score():
	var world = get_tree().get_nodes_in_group("play")[0] as World
	var current_score = world.score
	arr_score.append(world.score)
	var f = FileAccess.open(save_file, FileAccess.WRITE)
	f.store_var(arr_score)
	f.close()

func load_score():
	if FileAccess.file_exists(save_file): 
		var f = FileAccess.open(save_file, FileAccess.READ)
		arr_score = f.get_var()
		print("load: ", arr_score)
		f.close()
	
# Called when the node enters the scene tree for the first time.
func _ready():
	process_mode = Node.PROCESS_MODE_ALWAYS # 菜单，不受暂停影响
	layer.hide()
	rank.hide()
	load_score()

var isPause = false

func pause():
	isPause = true
	get_tree().paused = isPause
	layer.show()
	
func resume():
	isPause = false
	get_tree().paused = isPause
	layer.hide()
	rank.hide()

func quit():
	save_score()
	get_tree().quit()
	
func _input(event):
	if event.is_action_pressed("k_menu"):
		if not isPause:
			pause()
		else:
			resume()

func retry():
	save_score()
	var world_tmpl = load("res://scenes/world/world.tscn")
	var tree = get_tree()
	tree.change_scene_to_packed(world_tmpl)
	resume()
	
func show_rank():
	var rank_layer = $RankLayer as RankLayer
	print("show rank ", arr_score)
	rank_layer.setScore(arr_score)
	rank.show()
	
func _on_continue_pressed():
	resume()

func _on_quit_pressed():
	quit()
	
func _on_retry_pressed():
	retry()

func _on_rank_pressed():
	show_rank()
